<template>
  <el-dialog v-model="dialogFormVisible" :title="buttonName">
    <el-form :model="dialogForm" :rules="dialogFormRules" ref="dialogFormRef">
      <el-form-item v-if="!integration" label="审批人" prop="hissCreateUserName" :label-width="120">
        <el-input v-model="dialogForm.hissCreateUserName" autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="!integration" label="审批人ID" prop="hissCreateUserId" :label-width="120">
        <el-input v-model="dialogForm.hissCreateUserId" autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="!integration" label="审批人Group" prop="hissCreateUserGroups" :label-width="120">
        <el-input v-model="dialogForm.hissCreateUserGroups" autocomplete="off" />
      </el-form-item>

      <!-- 选择用户，如果是管理者模式，则输入，否则选择-->
      <template v-if="fieldName=='userName'">
        <el-form-item v-if="fieldLabel && !integration" :label="fieldLabel" :prop="fieldName" :label-width="120">
          <el-input v-model="inputData" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="!integration" :label="fieldLabel+'ID'" :prop="userId" :label-width="120">
          <el-input v-model="userId" autocomplete="off" />
        </el-form-item>
        <!-- 如果是发布模式，则通过搜索框来选择用户 -->
        <el-form-item v-if="integration" :label="fieldLabel" :prop="userId" :label-width="120">
          <SelectQuery title="用户" :tenant="flowInfo.processInfo.tenantId" :ok="handleUser" :max="1" />
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item v-if="fieldLabel" :label="fieldLabel" :prop="fieldName" :label-width="120">
          <el-input v-model="inputData" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" autocomplete="off" />
        </el-form-item>
      </template>

      <el-form-item v-if="name=='trigger'" :label="fieldLabel" prop="type" :label-width="120">
        <el-select v-model="dialogForm.type" placeholder="Select">
          <el-option
              v-for="item in triggerTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="name=='rollback'||name=='jump'||name=='withdraw'" :label="buttonName+'到节点'" prop="jumpTaskOrActivityId" :label-width="120">
        <el-select v-model="dialogForm.jumpTaskOrActivityId" placeholder="Select">
          <el-option
              v-for="item in jumpTaskOrActivityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="!integration" v-show="variable" label="新增变量" :prop="userId" :label-width="120">
        <el-table
            :data="variables"
            fixed >
          <el-table-column prop="name" label="属性名">
            <template #default="scope">
              <span v-show="!scope.row.edit">{{ scope.row.name }}</span>
              <el-input
                  v-show="scope.row.edit"
                  v-model="scope.row.name"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="属性值">
            <template #default="scope">
              <span v-show="!scope.row.edit">{{ scope.row.value }}</span>
              <el-input
                  v-show="scope.row.edit"
                  v-model="scope.row.value"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column align="right" label="">
            <template #default="scope">
              <el-button  size="small" @click="handleAdd(scope.$index, scope.row)">Add</el-button>
              <el-button
                  v-if="variables.length>1"
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"  >Delete</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handlerOk">
          {{buttonName}}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {processActionApprove} from "@/api/DevForDesignApi";
import messauthManager from '@/utils/user'
import SelectQuery from './SelectQuery'

export default {
  name: "OperateDialog",
  components:{SelectQuery},
  props:{
    name:{
      type:String,
      default:''
    },
    // 是否集成模式，集成模式不会让输入用户等信息
    integration:{
      type:Boolean,
      default: false
    },
    buttonName:{
      type:String,
      default:'确定'
    },
    fieldName:{
      type:String,
      default:'comment'
    },
    fieldLabel:{
      type:String,
      default:''
    },
    fun:{
      type:Function,
      default:null
    },
    refreshData:{
      type:Function,
      default:null
    },
    flowInfo:{
      type:Object,
      default:null
    },
    variable:{
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      //
      jumpTaskOrActivityOptions:[],
      // 触发的类型
      triggerTypes:[{label:'消息',value:'MSG'},{label:'信号',value:'SIGN'},{label:'补偿',value:'COP'}],
      // 动态字段
      inputData:'',
      //
      userId:'888',
      dialogFormVisible:false,
      //
      dialogForm:{
        hissCreateUserId:"1671403256519077890",
        hissCreateUserName:"王财务",
        hissCreateUserGroups:'',
        jumpTaskOrActivityId:"#start",
        type:'MSG',
      },
      dialogFormRules:{
        hissCreateUserName:[{
          required: true,
          message: '审批人是必填的',
          trigger: 'blur',
        }],
        hissCreateUserId:[{
          required: true,
          message: '审批人ID是必填的',
          trigger: 'blur',
        }]
      },
      variables:[{edit:true}]
    }
  },
  mounted(){
    const localData = messauthManager.getMessageAuth()
    this.dialogForm.hissCreateUserId = localData.currentUser.userId || ''
    this.dialogForm.hissCreateUserName = localData.currentUser.userName || ''
  },
  watch:{
    flowInfo:function (newVal,oldVal){
      if(this.name=='rollback'||this.name=='withdraw'){
        this.jumpTaskOrActivityOptions = []
        this.jumpTaskOrActivityOptions.push({label:'发起节点',value:'#start'})
        this.jumpTaskOrActivityOptions.push({label:'上一个节点',value:'#prev'})
        if(this.flowInfo&&this.flowInfo.nodes){
          let list = this.flowInfo.nodes
          for (let i = 0; i <list.length; i++) {
            let temp = list[i]
            if(temp.activityType=='UserTask'||temp.activityType=='userTask'){
              if(temp.status=='COMPLETE'){
                this.jumpTaskOrActivityOptions.push({label:temp.name,value:temp.id})
              }
              if(temp.taskId){
                for (let j = 0; j < this.flowInfo.activeTasks.length; j++) {
                  let activeTask = this.flowInfo.activeTasks[j];
                  if(activeTask.taskId==temp.taskId){
                    return;
                  }
                }
              }
            }
          }
        }
      }
      if(this.name=='jump'){
        this.jumpTaskOrActivityOptions = []
        if(this.flowInfo&&this.flowInfo.nodes){
          let list = this.flowInfo.nodes
          for (let i = 0; i <list.length; i++) {
            let temp = list[i]
            if(temp.activityType=='UserTask'||temp.activityType=='userTask'){
              this.jumpTaskOrActivityOptions.push({label:temp.name,value:temp.id})
            }
          }
        }
      }
    }
  },
  methods:{
    // 选择用户
    handleUser(result){
      this.userId = ''
      this.userName =''
      if(result.length==1){
        this.userId = result[0].id
        this.inputData = result[0].name
      }
    },
    handleAdd(index,row){
      this.variables.push({edit:true})
    },
    handleDelete(index,row){
      this.variables.splice(index,1)
    },
    // 通过用户名查找对应的任务信息
    // 如果用户名匹配，则返回对应的任务
    // 如果用户名不匹配，则返回未分配的任务
    findTaskUserName(userId){
      if(this.flowInfo&&this.flowInfo.activeTasks){
        let activeTasks = this.flowInfo.activeTasks
        let temp;
        for (let i = 0; i < activeTasks.length; i++) {
          let activeTask = activeTasks[i];
          if(activeTask.assignee==userId){
            return activeTask
          }
          if(this.name=='claim'||this.name=='unclaim'||this.name=='cancel'||this.name=='withdraw'){// 如果是认领、归还，则默认返回第一个任务
            temp = activeTask;
            break
          }
        }
        return temp;
      }
    },
    // 解决流程初始化不显示的问题
    show(){
      // 知晓在集成模式下，直接触发，不用弹窗
      if(this.integration&&this.name=='read'){
        this.handlerOk()
      }else{
        this.dialogFormVisible=true
      }
    },
    // 同意
    handlerOk(){
      let _this = this
      this.$refs.dialogFormRef.validate((valid,fields)=>{
        if(valid){
          // 构建用户信息
          let messageAuth = {
            currentUser:{
              userId:this.dialogForm.hissCreateUserId,
              userName:this.dialogForm.hissCreateUserName,
              userGroups:this.dialogForm.hissCreateUserGroups
            }
          }
          // 构建变量信息
          let tempVariables = {}
          for (let i = 0; i < this.variables.length; i++) {
            let variable = this.variables[i];
            if(variable.name&&variable.value){
              tempVariables[variable.name]=variable.value
            }
          }
          // 查找task信息
          let task = this.findTaskUserName(this.dialogForm.hissCreateUserId);
          if(!task&&this.flowInfo){
            this.dialogFormVisible=false
            this.$notify.warning({
              title: '提示',
              message: '没有您需要办理的任务，操作取消',
              showClose: true,
            })
            return
          }
          // 构建用户信息
          let formData = {
            operatorName:this.buttonName,
            variables:tempVariables,
            type:this.dialogForm.type,
            jumpTaskOrActivityId:this.dialogForm.jumpTaskOrActivityId
          }
          if(task){
            formData['taskId']=task.taskId
          }
          if(this.fieldName){
            formData[this.fieldName]=this.inputData
          }
          if(this.fieldName=='userName'){
            formData['userId']=this.userId
          }
          this.fun(formData,messageAuth).then(res => {
            if(res.code==200||res.success){
              this.dialogFormVisible=false
              this.$notify.success({
                title: '提示',
                message: '操作完成',
                showClose: true,
              })
              if(this.refreshData){
                this.refreshData()
              }
            }else{
              let temp = res.errorMessage
              let msg = temp
              try {
                msg = eval("(" + temp + ")")
                msg = msg.msg || temp
              } catch (e) {
              }
              this.$notify.error({
                title: '提示',
                message: msg,
                showClose: false,
              })
            }
          })
        }else{
          this.$notify.error({
            title: '提示',
            message: '请填写完表单~',
            showClose: false,
          })
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
